package com.example.smartgreenhouse.controller;

import com.example.smartgreenhouse.entity.DeviceCurrent;
import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.annotation.Limit;
import com.example.smartgreenhouse.entity.LightOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.service.DeviceCurrentService;
import com.example.smartgreenhouse.service.LightService;
import com.example.smartgreenhouse.utils.ResponseWrapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gsas/api/v1/device/light")
@RequiredArgsConstructor
public class LightController {

    private final LightService lightService;

    private final DeviceCurrentService deviceCurrentService;

    @PostMapping("/control")
    @JwtToken
    @Limit(
            key = "controlLight",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> controlLight(
            @RequestBody @Valid LightControlRequest request) {
        try {
            Long lightId = request.getLightId() != null ? request.getLightId() : 3L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId() != null ? request.getOperatorId() : 1L;

            LightOperationLog operationLog = lightService.controlLight(
                    lightId,
                    greenhouseId,
                    request.getIsOn(),
                    operatorId
            );

            return ResponseEntity.ok(ResponseWrapper.success("灯光控制成功", operationLog));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @PostMapping("/auto_control")
    @JwtToken
    @Limit(
            key = "setLightAutoControl",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<?> autoControlLight(
            @RequestBody @Valid AutoLightControlRequest request) {
        try {
            Long lightId = request.getLightId() != null ? request.getLightId() : 1L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId() != null ? request.getOperatorId() : 1L;

            Map<String, Object> result = lightService.setLightAuto(lightId, greenhouseId, operatorId, request.getAction());
            return ResponseEntity.ok(result);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @GetMapping("/current")
    @Limit(
            key = "Light_current",                          // 限流标识（通常作为Key）
            permitsPerSecond = 40.0 / 60.0,                 // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getLightCurrentStatus(
            @RequestParam Long lightId) {
        try {
            DeviceCurrent lightCurrent = deviceCurrentService.getDeviceStatus("full_spectrum_LED_light", lightId);
            return ResponseEntity.ok(ResponseWrapper.success(
                    lightId + "号LED灯的状态获取成功", lightCurrent));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @GetMapping("/history/{lightId}")
    @JwtToken
    @Limit(
            key = "getLightHistoryOperation",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getLightHistory(@PathVariable Long lightId) {
        try {
            List<LightOperationLog> history = lightService.getLightHistory(lightId);
            return ResponseEntity.ok(ResponseWrapper.success("查询成功", history));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @Data
    public static class LightControlRequest {
        private Long lightId;
        private Long greenhouseId;
        
        @NotNull(message = "状态不能为空")
        private String isOn;

        private Long operatorId;
    }

    @Data
    public static class AutoLightControlRequest {
        private Long lightId;
        private Long greenhouseId;
        
        @NotNull(message = "操作不能为空")
        private Integer action;

        private Long operatorId;
    }
}
